using Microsoft.EntityFrameworkCore;
using MESData.ErrorCode;
using MESData.Infrastucture;
using MESData.ProductionPlan.API.DTO;
using MESBaseis.Domain.ZSHH;

namespace MESData.ProductionPlan.API.Services
{
    /// <summary>
    /// 项目服务实现类
    /// </summary>
    public class ProjectService : IProjectService
    {
        private readonly MyDbcontext _context;

        public ProjectService(MyDbcontext context)
        {
            _context = context;
        }

        /// <summary>
        /// 获取所有项目（用于下拉框选择）
        /// </summary>
        public async Task<ApiResult<List<ProjectSelectDto>>> GetAllProjectsAsync(ProjectQueryDto? queryDto = null)
        {
            try
            {
                var query = _context.Projects
                    .Where(p => !p.IsDeleted)
                    .AsQueryable();

                // 应用查询条件
                if (queryDto != null)
                {
                    if (!string.IsNullOrWhiteSpace(queryDto.ProjectName))
                    {
                        query = query.Where(p => p.ProjectName.Contains(queryDto.ProjectName));
                    }

                    if (!string.IsNullOrWhiteSpace(queryDto.ProjectNumber))
                    {
                        query = query.Where(p => p.ProjectNumber.Contains(queryDto.ProjectNumber));
                    }

                    if (!string.IsNullOrWhiteSpace(queryDto.Status))
                    {
                        query = query.Where(p => p.Status == queryDto.Status);
                    }

                    if (queryDto.OnlyActive)
                    {
                        query = query.Where(p => p.Status == "进行中" || p.Status == "启用");
                    }
                }

                var projects = await query
                    .OrderBy(p => p.ProjectName)
                    .Select(p => new ProjectSelectDto
                    {
                        Id = p.Id,
                        ProjectName = p.ProjectName,
                        ProjectNumber = p.ProjectNumber,
                        Status = p.Status
                    })
                    .ToListAsync();

                return new ApiResult<List<ProjectSelectDto>> { Code = ApiEnum.Success, Msg = "查询成功", Data = projects };
            }
            catch (Exception ex)
            {
                return new ApiResult<List<ProjectSelectDto>> { Code = ApiEnum.Error, Msg = ex.Message };
            }
        }

        /// <summary>
        /// 分页查询项目
        /// </summary>
        public async Task<ApiResult<List<ProjectDto>>> GetProjectsPageAsync(ProjectQueryDto queryDto)
        {
            try
            {
                var query = _context.Projects
                    .Where(p => !p.IsDeleted)
                    .AsQueryable();

                // 应用查询条件
                if (!string.IsNullOrWhiteSpace(queryDto.ProjectName))
                {
                    query = query.Where(p => p.ProjectName.Contains(queryDto.ProjectName));
                }

                if (!string.IsNullOrWhiteSpace(queryDto.ProjectNumber))
                {
                    query = query.Where(p => p.ProjectNumber.Contains(queryDto.ProjectNumber));
                }

                if (!string.IsNullOrWhiteSpace(queryDto.Status))
                {
                    query = query.Where(p => p.Status == queryDto.Status);
                }

                if (queryDto.OnlyActive)
                {
                    query = query.Where(p => p.Status == "进行中" || p.Status == "启用");
                }

                var projects = await query
                    .OrderByDescending(p => p.CreateTime)
                    .Select(p => new ProjectDto
                    {
                        Id = p.Id,
                        ProjectName = p.ProjectName,
                        ProjectNumber = p.ProjectNumber,
                        Description = p.Description,
                        Status = p.Status,
                        StartDate = p.StartDate,
                        EndDate = p.EndDate,
                        Creator = p.Creator,
                        CreateTime = p.CreateTime,
                        Updator = p.Updator,
                        UpdateTime = p.UpdateTime
                    })
                    .ToListAsync();

                return new ApiResult<List<ProjectDto>> { Code = ApiEnum.Success, Msg = "查询成功", Data = projects };
            }
            catch (Exception ex)
            {
                return new ApiResult<List<ProjectDto>> { Code = ApiEnum.Error, Msg = ex.Message };
            }
        }

        /// <summary>
        /// 根据ID获取项目详情
        /// </summary>
        public async Task<ApiResult<ProjectDto>> GetProjectByIdAsync(int id)
        {
            try
            {
                var project = await _context.Projects
                    .Where(p => !p.IsDeleted && p.Id == id)
                    .Select(p => new ProjectDto
                    {
                        Id = p.Id,
                        ProjectName = p.ProjectName,
                        ProjectNumber = p.ProjectNumber,
                        Description = p.Description,
                        Status = p.Status,
                        StartDate = p.StartDate,
                        EndDate = p.EndDate,
                        Creator = p.Creator,
                        CreateTime = p.CreateTime,
                        Updator = p.Updator,
                        UpdateTime = p.UpdateTime
                    })
                    .FirstOrDefaultAsync();

                if (project == null)
                {
                    return new ApiResult<ProjectDto> { Code = ApiEnum.Error, Msg = "项目不存在" };
                }

                return new ApiResult<ProjectDto> { Code = ApiEnum.Success, Msg = "查询成功", Data = project };
            }
            catch (Exception ex)
            {
                return new ApiResult<ProjectDto> { Code = ApiEnum.Error, Msg = ex.Message };
            }
        }

        /// <summary>
        /// 新增项目
        /// </summary>
        public async Task<ApiResult<bool>> CreateProjectAsync(ProjectDto dto, string operatorName)
        {
            try
            {
                var project = new Project
                {
                    ProjectName = dto.ProjectName,
                    ProjectNumber = dto.ProjectNumber,
                    Description = dto.Description,
                    Status = dto.Status,
                    StartDate = dto.StartDate,
                    EndDate = dto.EndDate,
                    Creator = operatorName,
                    CreateTime = DateTime.Now
                };

                _context.Projects.Add(project);
                await _context.SaveChangesAsync();

                return new ApiResult<bool> { Code = ApiEnum.Success, Msg = "新增成功", Data = true };
            }
            catch (Exception ex)
            {
                return new ApiResult<bool> { Code = ApiEnum.Error, Msg = ex.Message };
            }
        }

        /// <summary>
        /// 更新项目
        /// </summary>
        public async Task<ApiResult<bool>> UpdateProjectAsync(int id, ProjectDto dto, string operatorName)
        {
            try
            {
                var project = await _context.Projects
                    .FirstOrDefaultAsync(p => !p.IsDeleted && p.Id == id);

                if (project == null)
                {
                    return new ApiResult<bool> { Code = ApiEnum.Error, Msg = "项目不存在" };
                }

                project.ProjectName = dto.ProjectName;
                project.ProjectNumber = dto.ProjectNumber;
                project.Description = dto.Description;
                project.Status = dto.Status;
                project.StartDate = dto.StartDate;
                project.EndDate = dto.EndDate;
                project.Updator = operatorName;
                project.UpdateTime = DateTime.Now;

                await _context.SaveChangesAsync();

                return new ApiResult<bool> { Code = ApiEnum.Success, Msg = "更新成功", Data = true };
            }
            catch (Exception ex)
            {
                return new ApiResult<bool> { Code = ApiEnum.Error, Msg = ex.Message };
            }
        }

        /// <summary>
        /// 删除项目
        /// </summary>
        public async Task<ApiResult<bool>> DeleteProjectAsync(int id, string operatorName)
        {
            try
            {
                var project = await _context.Projects
                    .FirstOrDefaultAsync(p => !p.IsDeleted && p.Id == id);

                if (project == null)
                {
                    return new ApiResult<bool> { Code = ApiEnum.Error, Msg = "项目不存在" };
                }

                // 检查是否有关联的生产计划
                var hasProductionPlans = await _context.ProductionPlans
                    .AnyAsync(p => !p.IsDeleted && p.ProjectId == id);

                if (hasProductionPlans)
                {
                    return new ApiResult<bool> { Code = ApiEnum.Error, Msg = "该项目下存在生产计划，无法删除" };
                }

                project.IsDeleted = true;
                project.Updator = operatorName;
                project.UpdateTime = DateTime.Now;

                await _context.SaveChangesAsync();

                return new ApiResult<bool> { Code = ApiEnum.Success, Msg = "删除成功", Data = true };
            }
            catch (Exception ex)
            {
                return new ApiResult<bool> { Code = ApiEnum.Error, Msg = ex.Message };
            }
        }
    }
} 